﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraVerticalGrid.Events;
using Moonlite.ExtensionApi.ControlInterfaces;
using Moonlite.ExtensionApi.GlobalInterfaces;
using Moonlite.Platform.General;

namespace Moonlite.UI.Shell.Controls {
    public partial class Properties : UserControl, IProperties {
        private IProjectFile selectedFile;
        public IProjectFile SelectedFile {
            get { return selectedFile; }
            set {
                selectedFile = value;
                UpdateObject();
            }
        }

        public void SetObject(object target) {
            propertyGridControl.SelectedObject = target;
            SelectedFile = target is IProjectFile ? target as IProjectFile : null;
        }

        private void UpdateObject() {
            try {
                if (SelectedFile != null) propertyGridControl.SelectedObject = SelectedFile.CreateProperties();
                else propertyGridControl.SelectedObject = null;
            }
            catch (Exception exception) {
                Logger.Log += exception.Message + Environment.NewLine;
            }
        }

        private void SaveObject() {
            try {
                if (SelectedFile != null) SelectedFile.SetFileProperties((FrontEndProjectFileProperties)propertyGridControl.SelectedObject);
            }
            catch (Exception exception) {
                Logger.Log += exception.Message + Environment.NewLine;
            }
        }

        private void OnPropertyGridControlRowChanged(object sender, RowChangedEventArgs e) {
            SaveObject();
        }

        public Properties() {
            InitializeComponent();
            try { Global.Instance.RegisterService(this, GetType().GetInterface("IProperties")); }
            catch { }
        }
    }
}
